﻿using Abp.Application.Services;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using iTextSharp.text;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.WeChat;
using SportsPlatform.Enums;
using SportsPlatform.Helpers;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Query.WeChat;
using SportsPlatform.WeChat.IWeChat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static iTextSharp.text.pdf.AcroFields;

namespace SportsPlatform.WeChat.WeChat
{
    /// <summary>
    /// 首页接口实现类
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class IndexService : SportsPlatformAppServiceBase, IIndexService
    {

        #region 私有变量

        private readonly IRepository<Competition, Guid> comRepository;
        private readonly IRepository<CompetitionProject, Guid> projectRepository;
        private readonly IRepository<RegistrationInfo, Guid> regRepository;
        private readonly IRepository<CompetitionAchievementInfo, Guid> compachieRepository;
        private readonly IRepository<CompetitionGroupingInfo, Guid> compgroupRepository;
        private readonly IRepository<Employee, Guid> employeeRepository;
        private readonly IRepository<CompeteTeam, Guid> comteamRepository;
        private readonly IRepository<CompeteTeamEmployee, Guid> comteamempRepository;
        private readonly IRepository<CompanyInfo, Guid> companyRepository;
        private readonly IRepository<EventsSession, Guid> eventsessRepository;
        private readonly IRepository<GroupingEmployeeInfo, Guid> groupemployeeRepository;




        #endregion

        #region 构造函数

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="_comRepository"></param>
        /// <param name="_projectRepository"></param>
        /// <param name="_regRepository"></param>
        /// <param name="_compachieRepository"></param>
        /// <param name="_compgroupRepository"></param>
        /// <param name="_employeeRepository"></param>
        /// <param name="_groupemployeeRepository"></param>
        /// <param name="_comteamRepository"></param>
        /// <param name="_comteamempRepository"></param>
        /// <param name="_companyRepository"></param>
        /// <param name="_eventsessRepository"></param>
        /// <param name="context"></param>
        public IndexService(IRepository<Competition, Guid> _comRepository,
            IRepository<CompetitionProject, Guid> _projectRepository,
            IRepository<RegistrationInfo, Guid> _regRepository,
            IRepository<CompetitionAchievementInfo, Guid> _compachieRepository,
            IRepository<CompetitionGroupingInfo, Guid> _compgroupRepository,
            IRepository<Employee, Guid> _employeeRepository,
            IRepository<GroupingEmployeeInfo, Guid> _groupemployeeRepository,
            IRepository<CompeteTeam, Guid> _comteamRepository,
            IRepository<CompeteTeamEmployee, Guid> _comteamempRepository,
            IRepository<CompanyInfo, Guid> _companyRepository,
            IRepository<EventsSession, Guid> _eventsessRepository,
            IHttpContextAccessor context) : base(context)
        {
            comRepository = _comRepository;
            projectRepository = _projectRepository;
            regRepository = _regRepository;
            compachieRepository = _compachieRepository;
            compgroupRepository = _compgroupRepository;
            employeeRepository = _employeeRepository;
            comteamRepository = _comteamRepository;
            comteamempRepository = _comteamempRepository;
            companyRepository = _companyRepository;
            eventsessRepository = _eventsessRepository;
            groupemployeeRepository = _groupemployeeRepository;
        }

        #endregion

        #region 公共API接口

        /// <summary>
        ///  赛事列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetHotCompetitionListDto>> GetHotCompetitionList(GetHotCompetitionListQuery query)
        {
            var res = new PagePagingDto<GetHotCompetitionListDto>();
            var listdto = new List<GetHotCompetitionListDto>();
            var list = new List<Competition>();
            var com = new List<Competition>();
            try
            {
                if (!string.IsNullOrEmpty(query.KeyWord))
                {
                    com = await comRepository.GetAllListAsync(a => a.Name.Contains(query.KeyWord) && (a.State == (int)CompetitionStateEnum.报名未开始 || a.State == (int)CompetitionStateEnum.正在报名 || a.State == (int)CompetitionStateEnum.报名结束待比赛));
                }
                else
                {
                    com = await comRepository.GetAllListAsync(a => a.State == (int)CompetitionStateEnum.报名未开始 || a.State == (int)CompetitionStateEnum.正在报名 || a.State == (int)CompetitionStateEnum.报名结束待比赛);
                }

                if (com.Count > query.PageSize)
                {
                    list.AddRange(com.Where(a => a.State == (int)CompetitionStateEnum.正在报名).OrderByDescending(a => a.CreateTime));
                    list.AddRange(com.Where(a => a.State == (int)CompetitionStateEnum.报名未开始).OrderByDescending(a => a.CreateTime));
                    list.AddRange(com.Where(a => a.State == (int)CompetitionStateEnum.报名结束待比赛).OrderByDescending(a => a.CreateTime));

                    list = list.Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize).ToList();

                    res.Message = "查询成功";
                    res.IsSuccess = true;
                    res.Code = HttpResultCode.Success;

                }
                else if (com.Count > 0)
                {
                    list.AddRange(com.Where(a => a.State == (int)CompetitionStateEnum.正在报名).OrderByDescending(a => a.CreateTime));
                    list.AddRange(com.Where(a => a.State == (int)CompetitionStateEnum.报名未开始).OrderByDescending(a => a.CreateTime));
                    list.AddRange(com.Where(a => a.State == (int)CompetitionStateEnum.报名结束待比赛).OrderByDescending(a => a.CreateTime));

                    res.Message = "查询成功";
                    res.IsSuccess = true;
                    res.Code = HttpResultCode.Success;
                }
                else
                {
                    list = null;
                    res.TotalCount = 0;
                    res.Code = HttpResultCode.NotData;
                    res.IsSuccess = false;
                    res.Message = "未查询到数据";
                }
                if (list != null)
                {
                    foreach (var item in list)
                    {
                        var dto = new GetHotCompetitionListDto();
                        dto.State = item.State;
                        dto.Id = item.Id;
                        dto.CoverPicture = item.CoverPicture;
                        dto.Name = item.Name;
                        dto.City = item.City;
                        dto.SingUpEndTime = item.SingUpEndTime;
                        dto.MatchTime = item.MatchBeginTime.ToString("yyyy.MM.dd") + " ～ " + item.MatchEndTime.ToString("MM.dd");
                        if (item.ChargeType == 2)
                        {
                            if (item.Money > 0)
                            {
                                dto.Money = "￥" + item.Money.ToString();
                            }
                            else
                            {
                                dto.Money = "免费";
                            }
                        }
                        else
                        {
                            var project = await projectRepository.GetAllListAsync(a => a.CompetitionId == item.Id && a.State > 0);
                            if (project.Count > 0)
                            {
                                dto.Money = "￥" + project.OrderBy(a => a.CostMoney).FirstOrDefault().CostMoney.ToString() + " ～ " + project.OrderByDescending(a => a.CostMoney).FirstOrDefault().CostMoney.ToString();
                            }
                        }

                        //获取当前赛事的报名人数，一个人参加多个项目时，人数只算一个
                        var reg = regRepository.GetAllList(a => a.CompetitionId == item.Id && a.RegistrationStatus == (int)RegistrationStatusEnum.报名成功 && a.IsDeleted == false).GroupBy(a => a.CompeteIdNo).Count();
                        dto.SignPeopleCount = reg;
                        listdto.Add(dto);
                    }
                    res.Data = listdto;
                }
                else
                {
                    res.Data = null;
                }

                res.TotalCount = com.Count;

            }
            catch (Exception ex)
            {
                res.TotalCount = 0;
                res.Data = null;
                res.Code = HttpResultCode.Error;
                res.IsSuccess = false;
                res.Message = ex.Message;
            }

            return res;
        }

        /// <summary>
        /// 获取赛事详情
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetIndexCompetitionDetailsDto>> GetCompetitionDetails(GetCompetitionDetailsQuery query)
        {
            var res = new ResultDto<GetIndexCompetitionDetailsDto>();
            var com = await comRepository.FirstOrDefaultAsync(query.Id);
            var project = await projectRepository.GetAllListAsync(a => a.CompetitionId == query.Id && a.State > 0);
            var dto = new GetIndexCompetitionDetailsDto();
            if (com != null)
            {
                dto.Id = com.Id;
                dto.CoverPicture = com.CoverPicture;
                dto.Point = com.Point;
                dto.Merchants = com.Merchants;
                dto.RotationPicture = com.RotationPicture.Split(',').ToList();
                dto.State = com.State;
                dto.StateStr = ConvertStatus(com.State);
                dto.Name = com.Name;
                dto.City = com.City;
                dto.Address = com.Address;
                dto.Details = com.Details;
                dto.DetailsAddress = com.DetailsAddress;
                dto.Instructions = com.Instructions;
                dto.MatchTime = com.MatchBeginTime.ToString("yyyy.MM.dd") + " ～ " + com.MatchEndTime.ToString("MM.dd");
                dto.SignUpTime = com.SignUpBeginTime.ToString("yyyy.MM.dd HH:ss") + " ～ " + com.SingUpEndTime.ToString("MM.dd HH:ss");
                if (com.ChargeType == 2)
                {
                    if (com.Money > 0)
                    {
                        dto.Money = "￥" + com.Money.ToString() + "/人";
                    }
                    else
                    {
                        dto.Money = "免费";
                    }
                }
                else
                {
                    dto.Money = "￥" + project.OrderBy(a => a.CostMoney).FirstOrDefault().CostMoney.ToString() + " ～ " + project.OrderByDescending(a => a.CostMoney).FirstOrDefault().CostMoney.ToString() + "/人";
                }
                var race = new List<Raceschedule>();
                project = project.OrderBy(a => a.GameBeginTime).ToList();
                foreach (var item in project)
                {
                    var r = new Raceschedule();
                    r.Project = item.Name;
                    r.Address = item.Stadium;
                    r.Date = item.GameBeginTime.ToString("yyyy-MM-dd");
                    r.Time = item.GameBeginTime.ToString("HH:ss") + " ～ " + (item.GameBeginTime.Date == item.GameEndTime ? item.GameEndTime.ToString("HH:ss") : item.GameEndTime.ToString("yyyy-MM-dd HH:mm"));
                    race.Add(r);
                }
                dto.Raceschedules = race;

                //获取推荐赛事
                var listrec = new List<GetHotCompetitionListDto>();
                var recommend = comRepository.GetAllList().Where(a => a.State == (int)CompetitionStateEnum.正在报名 && a.Id != com.Id).OrderByDescending(a => a.CreateTime);
                if (recommend.Count() > 0)
                {
                    foreach (var item in recommend)
                    {
                        var rec = new GetHotCompetitionListDto();
                        rec.State = item.State;
                        rec.Id = item.Id;
                        rec.CoverPicture = item.CoverPicture;
                        rec.Name = item.Name;
                        rec.City = item.City;
                        rec.SingUpEndTime = item.SingUpEndTime;
                        rec.MatchTime = item.MatchBeginTime.ToString("yyyy.MM.dd") + " ～ " + item.MatchEndTime.ToString("MM.dd");
                        if (item.ChargeType == 2)
                        {
                            if (item.Money > 0)
                            {
                                rec.Money = "￥" + item.Money.ToString();
                            }
                            else
                            {
                                rec.Money = "免费";
                            }
                        }
                        else
                        {
                            var pro = await projectRepository.GetAllListAsync(a => a.CompetitionId == item.Id && a.State > 0);
                            if (pro.Count > 0)
                            {
                                rec.Money = "￥" + pro.OrderBy(a => a.CostMoney).FirstOrDefault().CostMoney.ToString() + " ～ " + pro.OrderByDescending(a => a.CostMoney).FirstOrDefault().CostMoney.ToString();
                            }
                            else
                            {
                                rec.Money = "0";
                            }
                        }

                        //获取当前赛事的报名人数，一个人参加多个项目时，人数只算一个
                        var reg = regRepository.GetAllList(a => a.CompetitionId == item.Id && a.RegistrationStatus == (int)RegistrationStatusEnum.报名成功 && a.IsDeleted == false).GroupBy(a => a.CompeteIdNo).Count();
                        rec.SignPeopleCount = reg;
                        listrec.Add(rec);
                    }

                    dto.Recommend = listrec;
                }
                res.IsSuccess = true;
                res.Message = "查询成功！";
                res.Code = HttpResultCode.Success;
                res.Data = dto;
            }
            else
            {
                res.IsSuccess = false;
                res.Message = "未查询到数据";
                res.Code = HttpResultCode.NotData;
            }
            return res;
        }

        /// <summary>
        /// 获取赛事比赛项目
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetCompetitionProjectListDto>> GetCompetitionProjectList(GetCompetitionProjectListQuery query)
        {
            var res = new ResultDto<GetCompetitionProjectListDto>();
            var com = await comRepository.FirstOrDefaultAsync(query.Id);
            var project = await projectRepository.GetAllListAsync(a => a.CompetitionId == query.Id && a.State > 0);
            var dto = new GetCompetitionProjectListDto();
            if (com != null)
            {
                dto.RotationPicture = com.CoverPicture.Split(',').ToList();
                dto.Name = com.Name;
                dto.City = com.City;
                dto.Address = com.Address;
                dto.DetailsAddress = com.DetailsAddress;
                dto.MatchTime = com.MatchBeginTime.ToString("yyyy.MM.dd") + " ～ " + com.MatchEndTime.ToString("MM.dd");
                dto.SignUpTime = com.SignUpBeginTime.ToString("yyyy.MM.dd HH:ss") + " ～ " + com.SingUpEndTime.ToString("MM.dd HH:ss");

                var race = new List<Raceschedule>();
                project = project.OrderBy(a => a.GameBeginTime).ToList();
                foreach (var item in project)
                {
                    var r = new Raceschedule();
                    r.Project = item.Name;
                    r.Address = item.Stadium;
                    r.Date = item.GameBeginTime.ToString("yyyy-MM-dd");
                    r.Time = item.GameBeginTime.ToString("HH:ss") + " ～ " + (item.GameBeginTime.Date == item.GameEndTime.Date ? item.GameEndTime.ToString("HH:mm") : item.GameEndTime.ToString("yyyy-MM-dd HH:mm"));
                    race.Add(r);
                }
                dto.Raceschedules = race;

                //获取推荐赛事
                var listrec = new List<GetHotCompetitionListDto>();
                var recommend = comRepository.GetAllList().Where(a => a.State == (int)CompetitionStateEnum.正在报名 && a.Id != com.Id).OrderByDescending(a => a.CreateTime);
                if (recommend.Count() > 0)
                {
                    foreach (var item in recommend)
                    {
                        var rec = new GetHotCompetitionListDto();
                        rec.State = item.State;
                        rec.Id = item.Id;
                        rec.CoverPicture = item.CoverPicture;
                        rec.Name = item.Name;
                        rec.City = item.City;
                        rec.SingUpEndTime = item.SingUpEndTime;
                        rec.MatchTime = item.MatchBeginTime.ToString("yyyy.MM.dd") + " ～ " + item.MatchEndTime.ToString("MM.dd");
                        if (item.ChargeType == 2)
                        {
                            if (item.Money > 0)
                            {
                                rec.Money = "￥" + item.Money.ToString();
                            }
                            else
                            {
                                rec.Money = "免费";
                            }
                        }
                        else
                        {
                            var pro = await projectRepository.GetAllListAsync(a => a.CompetitionId == item.Id && a.State > 0);
                            rec.Money = "￥" + pro.OrderBy(a => a.CostMoney).FirstOrDefault().CostMoney.ToString() + " ～ " + pro.OrderByDescending(a => a.CostMoney).FirstOrDefault().CostMoney.ToString();
                        }

                        //获取当前赛事的报名人数，一个人参加多个项目时，人数只算一个
                        var reg = regRepository.GetAllList(a => a.CompetitionId == item.Id && a.RegistrationStatus == (int)RegistrationStatusEnum.报名成功 && a.IsDeleted == false).GroupBy(a => a.CompeteIdNo).Count();
                        rec.SignPeopleCount = reg;
                        listrec.Add(rec);
                    }
                }
            }
            return res;
        }

        /// <summary>
        /// 通过查询条件获取分页后的赛事列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetHotCompetitionListDto>> GetCompetitionList(GetCompetitionListQuery query)
        {
            PagePagingDto<GetHotCompetitionListDto> resultDto = new PagePagingDto<GetHotCompetitionListDto>();
            try
            {
                var competitions = new List<GetHotCompetitionListDto>();
                var types = await comRepository.GetAllListAsync(i => i.IsDeleted == false && i.State != 0 && i.State != 1);
                types = types.WhereIf(!query.Keywords.IsNullAndEmpty(), t => t.Name.Contains(query.Keywords)).ToList();
                if (types.Count > 0)
                {

                    var pages = types.Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize).ToList();
                    var res = await regRepository.GetAllListAsync(i => i.IsDeleted == false && i.RegistrationStatus != 1);
                    foreach (var item in pages)
                    {
                        var re = res.Where(i => i.CompetitionId == item.Id).ToList();
                        var dto = new GetHotCompetitionListDto
                        {
                            SignPeopleCount = re.Count,
                            City = item.City,
                            CoverPicture = item.CoverPicture,
                            Name = item.Name,
                            State = item.State,
                            Id = item.Id,
                            MatchTime = item.MatchBeginTime.ToString("yyyy.MM.dd") + "-" + item.MatchEndTime.ToString("MM.dd"),
                        };
                        if (item.ChargeType == 2)
                        {
                            if (item.Money > 0)
                            {
                                dto.Money = "￥" + item.Money.ToString();
                            }
                            else
                            {
                                dto.Money = "免费";
                            }
                        }
                        else
                        {
                            var project = await projectRepository.GetAllListAsync(a => a.CompetitionId == item.Id && a.State > 0);
                            if (project.Count > 0)
                            {
                                dto.Money = "￥" + project.OrderBy(a => a.CostMoney).FirstOrDefault().CostMoney.ToString() + " ～ " + project.OrderByDescending(a => a.CostMoney).FirstOrDefault().CostMoney.ToString();
                            }
                        }
                        competitions.Add(dto);

                    }
                    resultDto.Data = competitions;
                    resultDto.TotalCount = types.Count;
                }
                resultDto.Code = types.Count > 0 ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = types.Count > 0;
                resultDto.Message = types.Count > 0 ? "获取成功" : "获取失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 转换状态
        /// </summary>
        /// <param name="status">赛事状态（0：关闭；1：待发布；2：报名未开始；3：正在报名；4：报名结束待比赛；5：正在比赛；6：比赛结束）</param>
        /// <returns></returns>
        private string ConvertStatus(int status)
        {
            var str = "";
            switch (status)
            {
                case 0:
                    str = "关闭";
                    break;
                case 1:
                    str = "待发布";
                    break;
                case 2:
                    str = "报名未开始";
                    break;
                case 3:
                    str = "正在报名";
                    break;
                case 4:
                    str = "报名结束待比赛";
                    break;
                case 5:
                    str = "正在比赛";
                    break;
                case 6:
                    str = "比赛结束";
                    break;
            }
            return str;
        }

        /// <summary>
        /// 根据年份获取赛事名称
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetYearCompetitionNameDto>> GetYearCompetitionName(GetYearCompetitionNameQuery query)
        {
            ResultListDto<GetYearCompetitionNameDto> resultListDto = new ResultListDto<GetYearCompetitionNameDto>();
            try
            {
                var ret = (await comRepository.GetAllListAsync(info => info.MatchBeginTime.Year.ToString().Equals(query.ParticularYear) && info.IsEnable == 1 && info.State == 6 && info.IsDeleted == false)).OrderByDescending(info => info.CreateTime);
                if (ret != null && ret.Count() > 0)
                {
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.IsSuccess = true;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = ObjectMapper.Map<List<GetYearCompetitionNameDto>>(ret);
                    resultListDto.Count = ret.Count();
                }
                else
                {
                    resultListDto.Code = HttpResultCode.NotData;
                    resultListDto.IsSuccess = false;
                    resultListDto.Message = "未查询到相关年份的赛事名称！";
                }
            }
            catch (Exception e)
            {
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.IsSuccess = false;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }

        /// <summary>
        /// 获取赛事项目名称集合
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetCompetitionProjectNameDto>> GetCompetitionProjectName(GetCompetitionProjectNameQuery query)
        {
            ResultListDto<GetCompetitionProjectNameDto> resultListDto = new ResultListDto<GetCompetitionProjectNameDto>();
            try
            {
                var ret = (await projectRepository.GetAllListAsync(info => info.CompetitionId == query.CompetitionId && info.IsDeleted == false && info.State == 6)).OrderByDescending(info => info.CreateTime);
                if (ret != null && ret.Count() > 0)
                {
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.IsSuccess = true;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = ObjectMapper.Map<List<GetCompetitionProjectNameDto>>(ret);
                    resultListDto.Count = ret.Count();
                }
                else
                {
                    resultListDto.Code = HttpResultCode.NotData;
                    resultListDto.IsSuccess = false;
                    resultListDto.Message = "未查询到相关赛事项目名称！";
                }
            }
            catch (Exception e)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }

        /// <summary>
        /// 获取成绩信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetAchievementInfoDto>> GetAchievementInfo(GetAchievementInfoQuery query)
        {
            ResultDto<GetAchievementInfoDto> resultDto = new ResultDto<GetAchievementInfoDto>();
            try
            {
                var ret = await compachieRepository.GetAllListAsync(info => info.CompetitionId == query.CompetitionId && info.CompetitionProjectId == query.CompetitionProjectId);
                
                var comprojectinfo = await projectRepository.FirstOrDefaultAsync(query.CompetitionProjectId);
                //身份证号 + 参赛人/团队姓名 二个条件
                var empinfo = await employeeRepository.FirstOrDefaultAsync(info => info.IDNumber == query.IDNumber && info.IsDeleted == false);
                //个人赛-团体赛
                var comteamemplist = await comteamempRepository.GetAllListAsync(info => info.IsDeleted == false && info.EmployeeId == empinfo.Id);
                //复杂的判断逻辑代码运行，怕数据库压力大
                var dto = ret.Where(info => comRepository.FirstOrDefault(com => com.Id == info.CompetitionId).MatchBeginTime.Year.ToString().Equals(query.ParticularYear)
                    && info.CompetitionRanking != null)
                    .Where(info=> info.ContestantOrTeam == query.ContestantOrTeam || empinfo.RealName == query.ContestantOrTeam)
                    .WhereIf(comprojectinfo.GameType==(int)CompetitionProjectTypeEnum.团队接力赛,info=> comteamemplist?.FirstOrDefault(a=>a.EventsSessionId==info.EventsSessionId)!=null)
                    .WhereIf(comprojectinfo.GameType == (int)CompetitionProjectTypeEnum.个人赛, info => info.EmployeeId==empinfo.Id)
                    .OrderByDescending(info => info.CreateTime).ToList().FirstOrDefault();
                if (dto != null)
                {
                    resultDto.Data = ObjectMapper.Map<GetAchievementInfoDto>(dto);
                   
                    resultDto.Data.EmployeeName = empinfo.RealName;
                    if (comprojectinfo.GameType == (int)CompetitionProjectTypeEnum.团队接力赛)
                    {
                        resultDto.Data.Sensor = comteamemplist?.FirstOrDefault(a => a.EventsSessionId == dto.EventsSessionId).Sensor;
                    }
                    else {
                        var groupempinfo = groupemployeeRepository.FirstOrDefault(info => info.Id == dto.CompetitionGroupingId && info.EmployeeId == dto.EmployeeId);
                        resultDto.Data.Sensor = groupempinfo.Sensor;
                    }
                   
                    resultDto.Data.FinalResults = dto.AchievementTime.ToString();
                    resultDto.Data.Qualifying = string.Format("第{0}名/{1}人", dto.CompetitionRanking.ToString(), ret.Count.ToString());
                    resultDto.Data.EventDirectorName = "";
                    resultDto.Data.PresidentJudgeName = "";
                    Guid compinfoid = comRepository.FirstOrDefault(com => com.Id == dto.CompetitionId).Merchants;
                    resultDto.Data.MerchantsName = companyRepository.FirstOrDefault(info => info.Id == compinfoid).CompanyName;
                    DateTime mattime = comRepository.FirstOrDefault(com => com.Id == dto.CompetitionId).MatchBeginTime;
                    resultDto.Data.CompetitionYears = YearConvertToChineseCapital(mattime.Year) + "年" + OtherConvertToChineseCapital(mattime.Month) + "月";
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "查询成功！";
                }
                else
                {
                    resultDto.Code = HttpResultCode.SqlError;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "未查询到成绩信息！";
                }
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 历史成绩获取
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<GetHistoryAchievementInfoDto>> GetHistoryAchievementInfo(GetHistoryAchievementInfoQuery query)
        {
            ResultListDto<GetHistoryAchievementInfoDto> resultListDto = new ResultListDto<GetHistoryAchievementInfoDto>();
            try
            {
                var comteamemplist = await comteamempRepository.GetAllListAsync(info => info.IsDeleted == false && info.EmployeeId == query.EmployeeId);
                var projectlist = (await compachieRepository.GetAllListAsync())
                    .Where(info => info.EmployeeId == query.EmployeeId ||comteamemplist.FirstOrDefault(a=>a.EventsSessionId==info.EventsSessionId)!=null)
                    .OrderBy(info => info.CreateTime)
                    .GroupBy(info => info.CompetitionProjectId).ToList();
                if (projectlist != null && projectlist.Count() > 0)
                {
                    List<GetHistoryAchievementInfoDto> dtos = new List<GetHistoryAchievementInfoDto>();
                    foreach (var item in projectlist)
                    {
                        GetHistoryAchievementInfoDto dto = new GetHistoryAchievementInfoDto();
                        dto.CompetitionProjectName = projectRepository.FirstOrDefault(info => info.Id == item.Key).Name;
                        var detailslist = (await compachieRepository.GetAllListAsync())
                            .Where(info => info.CompetitionProjectId == item.Key 
                            && (info.EmployeeId == query.EmployeeId || comteamemplist.FirstOrDefault(a => a.EventsSessionId == info.EventsSessionId) != null));
                        if (detailslist != null && detailslist.Count() > 0)
                        {
                            List<ProjectItem> projectlists = new List<ProjectItem>();
                            foreach (var det in detailslist)
                            {
                                ProjectItem projectItem = new ProjectItem();
                                projectItem.CompetitionRanking = (int)det.CompetitionRanking;
                                projectItem.EventsSessionName = det.CompetitionNode;//await GetEventsSessionName(det.EventsSessionId);
                                projectItem.AchievementCircleOrTime = ((int)det.AchievementCircle).ToString() + "/" + det.AchievementTime;
                                projectItem.BuckleRingOrTime = ((int)det.BuckleRing).ToString() + "/" + det.BuckleTime;
                                projectItem.ActualLap = (int)det.ActualLap;
                                projectItem.YellowOrRedCard = ((int)det.YellowCard).ToString() + "/" + ((int)det.RedCard).ToString(); ;
                                projectlists.Add(projectItem);
                            }
                            dto.ProjectList = projectlists;
                        }
                        if (dto.ProjectList != null && dto.ProjectList.Count > 0)
                        {
                            dtos.Add(dto);
                        }
                    }
                    if (dtos != null && dtos.Count > 0)
                    {
                        resultListDto.Code = HttpResultCode.Success;
                        resultListDto.IsSuccess = true;
                        resultListDto.Message = "查询成功！";
                        resultListDto.Data = dtos;
                        resultListDto.Count = dtos.Count;
                    }
                    else
                    {
                        resultListDto.Code = HttpResultCode.Fail;
                        resultListDto.IsSuccess = false;
                        resultListDto.Message = "未查询到数据！";
                    }
                }
                else
                {
                    resultListDto.Code = HttpResultCode.Error;
                    resultListDto.IsSuccess = false;
                    resultListDto.Message = "未查询到数据！";
                }
            }
            catch (Exception e)
            {
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.IsSuccess = false;
                resultListDto.Message = e.Message.ToString();
            }
            return resultListDto;
        }

        /// <summary>
        /// 首页获取热门赛事列表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ResultListDto<GetHotCompetitionListDto>> GetHotCompetitionList()
        {
            ResultListDto<GetHotCompetitionListDto> result = new ResultListDto<GetHotCompetitionListDto>();
            try
            {
                var listdto = new List<GetHotCompetitionListDto>();
                var res = await comRepository.GetAllListAsync(c => c.IsDeleted == false && c.IsEnable == 1 && c.State >= 3 && c.State <= 5);
                var projects = await projectRepository.GetAllListAsync(a => a.IsDeleted == false && a.State >= 2 && a.State <= 5);
                foreach (var item in res)
                {
                    var pros = projects.Where(p => p.CompetitionId == item.Id).ToList();
                    if (pros.Count > 0)
                    {
                        var dto = new GetHotCompetitionListDto();
                        dto.State = item.State;
                        dto.Id = item.Id;
                        dto.CoverPicture = item.CoverPicture;
                        dto.Name = item.Name;
                        dto.City = item.City;
                        dto.SingUpEndTime = item.SingUpEndTime;
                        dto.MatchTime = item.MatchBeginTime.ToString("yyyy.MM.dd") + " ～ " + item.MatchEndTime.ToString("MM.dd");
                        if (item.ChargeType == 2)
                        {
                            if (item.Money > 0)
                            {
                                dto.Money = "￥" + item.Money.ToString();
                            }
                            else
                            {
                                dto.Money = "免费";
                            }
                        }
                        else
                        {
                            if (pros.Count > 0)
                            {
                                dto.Money = "￥" + pros.OrderBy(a => a.CostMoney).FirstOrDefault().CostMoney.ToString() + " ～ " + pros.OrderByDescending(a => a.CostMoney).FirstOrDefault().CostMoney.ToString();
                            }
                        }

                        //获取当前赛事的报名人数，一个人参加多个项目时，人数只算一个
                        var reg = regRepository.GetAllList(a => a.CompetitionId == item.Id && a.RegistrationStatus == (int)RegistrationStatusEnum.报名成功 && a.IsDeleted == false).GroupBy(a => a.CompeteIdNo).Count();
                        dto.SignPeopleCount = reg;
                        listdto.Add(dto);
                    }
                }
                if (listdto.Count > 0)
                {
                    result.Count = listdto.Count;
                    result.Code = 200;
                    result.Data = listdto;
                    result.IsSuccess = true;
                    result.Message = "查询成功";
                }
                else
                {
                    result.Code = HttpResultCode.NotData;
                    result.IsSuccess = true;
                    result.Message = "未查询到数据";
                }
            }
            catch (Exception ex)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Message = ex.Message;
            }
            return result;
        }
        #endregion

        #region 私有方法

        /// <summary>
        /// 获取年
        /// </summary>
        /// <param name="year"></param>
        /// <returns></returns>
        private static string YearConvertToChineseCapital(int year)
        {
            string str = "";
            string yearStr = year.ToString();
            int n;
            for (int i = 0; i < year.ToString().Length; i++)
            {
                n = int.Parse(yearStr[i].ToString());
                switch (n)
                {
                    case 0: str = str + "零"; break;
                    case 1: str = str + "一"; break;
                    case 2: str = str + "二"; break;
                    case 3: str = str + "三"; break;
                    case 4: str = str + "四"; break;
                    case 5: str = str + "五"; break;
                    case 6: str = str + "六"; break;
                    case 7: str = str + "七"; break;
                    case 8: str = str + "八"; break;
                    default: str = str + "九"; break;
                }
            }
            return str;
        }
        /// <summary>
        /// 获取月
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        private static string OtherConvertToChineseCapital(int other)
        {
            string str = "";
            if (other < 10)
            {
                str = YearConvertToChineseCapital(other);
            }
            else
            {
                switch (other)
                {
                    case 10: str = "十"; break;
                    case 11: str = "十一"; break;
                    default: str = "十二"; break;
                }

            }
            return str;
        }
        #endregion
    }
}
